package com.ebelter.ty.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.ebelter.btcomlib.bases.activity.BaseActivity;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponse;
import com.ebelter.btcomlib.utils.MD5Utils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.SpUtil;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.ty.AppConfig;
import com.ebelter.ty.R;
import com.ebelter.ty.model.http.TyNetUtil;

import java.util.Calendar;


/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "LoginActivity";


    EditText et_name_login;


    EditText et_pwd_login;

    @Override
    protected void initView() {

        et_name_login=findViewById(R.id.et_name_login);
        et_pwd_login=findViewById(R.id.et_pwd_login);

        et_name_login.setOnClickListener(this);
        et_pwd_login.setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.tv_forgot_password).setOnClickListener(this);
        findViewById(R.id.tv_join_us_free).setOnClickListener(this);

    }

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_login;
    }



    protected void initViews() {
        StatusBarUtil.setTranslucent(this, 0);
    }

    @Override
    protected void initData() {

        long user_id = UserSpUtil.readLong(Constants.IUser.USER_ID,-1);
        String nick_name = UserSpUtil.readString(Constants.IUser.NICK_NAME);
        String btid = UserSpUtil.readString(Constants.IUser.BT_ID);

        AppConfig.getInstance().setKgModel(SpUtil.readBoolean(Constants.IUser.IS_KG_MODEL,true));//是否kg模式
        // Constants.isKgUnit= false;

        LogUtils.i(TAG,"----LoginActivity---A"+user_id);
        if (user_id>0&&!TextUtils.isEmpty(nick_name)&&!TextUtils.isEmpty(btid)){
            //说明已经登录了 直接登录吧
            startActivity(ScaleMainActivity.class);
            finish();
        }
    }





    //登录
    private void sign_in() {
        String name = et_name_login.getText().toString().trim();
        String psw = et_pwd_login.getText().toString().trim();


        if (TextUtils.isEmpty(name)){
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            return;
        }
        if (TextUtils.isEmpty(psw)){
            ToastUtil.show(R.string.The_password_cannot_be_empty);
            return;
        }
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        showLoadingDialog(StringUtils.getResStr(R.string.Log_in));
        TyNetUtil.getInstance().loginRequest(this, false, name, MD5Utils.getMd5(psw), new HttpResponse<LoginResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, LoginResponse loginResponse, String s) {
                dissLoadingDialog();
                if (isRequestSuccess){
                    LogUtils.e(TAG,"---loginRequest--loginResponse="+loginResponse);
                    if (loginResponse.resultCode==0){
                        //登录成功
                        saveUserDatas(loginResponse.getResultData());
                        startActivity(ScaleMainActivity.class);
                        finish();
                    }else if (loginResponse.getResultCode()==109){//109是：不存在的email或者昵称
                        ToastUtil.show(R.string.mail_nickname_no_exist);
                    }else if(loginResponse.getResultCode()==111){//111密码错误
                        ToastUtil.show(R.string.psw_error);
                    }else if (loginResponse.getResultCode()==110){//服务器异常
                        ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                    }
                    //הזן את הגובה שלך (%1$.1f ~ %2$.1f)

                }else {
                    ToastUtil.show(R.string.Network_connection_error);
                }
            }
        });




    }


    public static String userid2btid(long user_id){
        if (user_id<0){
            user_id=0;
        }
        String userid=user_id+"";
        if (userid.length()>14){
            userid=userid.substring(userid.length()-14,userid.length());
        }
        return userid;
    }



    //保存登录用户数据
    private void saveUserDatas(LoginResponse.ResultDataBean resultData) {
        UserSpUtil.removeAll();

        LogUtils.i(TAG,"----------"+resultData.toString());

        long useridlong = resultData.getUserId();
        UserSpUtil.writeLong(Constants.IUser.USER_ID,useridlong);

        // TODO: 2018/4/23 zcq
        String btId = ScaleUser.getUser().toBtId(userid2btid(useridlong));
        LogUtils.i(TAG, "-----loginSave--useridlong = " + useridlong);
        LogUtils.i(TAG, "-----loginSave--btId = " + btId);

        UserSpUtil.writeString(Constants.IUser.BT_ID,btId);
        UserSpUtil.writeString(Constants.IUser.NICK_NAME,resultData.getNickName());
        UserSpUtil.writeString(Constants.IUser.EMAIL,resultData.getEmail());
        UserSpUtil.writeInt(Constants.IUser.HEIGHT,resultData.getHeight());
        UserSpUtil.writeFloat(Constants.IUser.WEIGHT,resultData.getWeight());

        String birthday=resultData.getBirthday();
        UserSpUtil.writeString(Constants.IUser.BIRTHDAY,birthday);
        int year=getBirthdayIntValue(birthday,0,1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR,year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS,getBirthdayIntValue(birthday,1,6));
        UserSpUtil.writeInt(Constants.IUser.DAY,getBirthdayIntValue(birthday,2,1));
        UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));


        UserSpUtil.writeInt(Constants.IUser.SEX,resultData.getSex());
        UserSpUtil.writeInt(Constants.IUser.PROFESSION,resultData.getProfession());
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE,resultData.getImpedance());
        UserSpUtil.writeString(Constants.IUser.CREATEDATE,resultData.getCreateDate());
        UserSpUtil.writeString(Constants.IUser.UPDATEDATE,resultData.getUpdateDate());
        UserSpUtil.writeFloat(Constants.IUser.TARGET_WEIGHT,resultData.getTargetWeight());


    }

    private int getAgeByBirthday(int year){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-year;
    }

    private int getBirthdayIntValue(String string,int index,int defaultValue){
        if (TextUtils.isEmpty(string)){
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length!=3){
            return defaultValue;
        }
        return NumUtils.string2Int(args[index],defaultValue);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login://sign_in 登录
                sign_in();
                break;
            case R.id.tv_forgot_password://忘记密码
                startActivity(FindPswActivity.class);
                break;
            case R.id.ll_facebook:
                LogUtils.i(TAG,"----------facebook");
                break;
            case R.id.ll_twitter:
                LogUtils.i(TAG,"----------twitter");
                break;
            case R.id.ll_line:
                break;
            case R.id.tv_join_us_free:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
        }

    }
}
